#define _CRT_SECURE_NO_WARNINGS 1
#define K 3
#define N 10
#include <stdio.h>
#include <time.h>
#include <stdlib.h>

void xieru();
int* topK(int k);
void jiandui(int* arr, int k);
void swap(int* e1, int* e2);
void xiangshang(int* arr, int ch);
void xiangxia(int* arr, int pr, int k);

int main()
{
	xieru();
	int* arr = topK(K);
	for (int i = 0; i < K; i++) {
		printf("%d ", arr[i]);
	}
	free(arr);
	arr = NULL;
}

void xieru()
{
	srand(time(NULL));
	FILE* pf = fopen("data.txt", "w");
	if (pf == NULL)
	{
		perror("fopen error");
		return;
	}
	for (int i = 0; i < N; i++)
	{
		fprintf(pf, "%d\n", rand() + i);
	}
	fclose(pf);
	pf = NULL;
}

int* topK(int k) {
	int* ret = malloc(sizeof(int) * k);
	FILE* pf = fopen("data.txt", "r");
	if (pf == NULL)
	{
		perror("fopen error");
		return;
	}
	for (int i = 0; i < k; i++)
	{
		fscanf(pf, "%d", ret + i);
	}
	jiandui(ret, k);
	int tmp;
	while (fscanf(pf, "%d\n", &tmp)!=EOF) {
		if (tmp > ret[0]) {
			ret[0] = tmp;
			xiangxia(ret, 0, k);
		}
	}
	fclose(pf);
	return ret;
}

void xiangshang(int* arr, int ch) {
	int pr = (ch - 1) / 2;
	while (ch > 0 && arr[ch] < arr[pr]) {
		swap(arr + ch, arr + pr);
		ch = pr;
		pr = (ch - 1) / 2;
	}
}

void xiangxia(int* arr, int pr, int k) {
	int ch = pr * 2 + 1;
	while (ch < k) {
		if (ch + 1 < k && arr[ch + 1] < arr[ch]) ch++;
		if (arr[ch] < arr[pr]) {
			swap(arr + ch, arr + pr);
			pr = ch;
			ch = pr * 2 + 1;
		}
		else return;
	}
}

void jiandui(int* arr, int k)
{
	/*for (int i = 1; i < k; i++) {
		xiangshang(arr, i);
	}*/
	for (int i = (k - 2) / 2; i >= 0; i--) {
		xiangxia(arr, i, k);
	}
}

void swap(int* e1, int* e2)
{
	int tmp = *e1;
	*e1 = *e2;
	*e2 = tmp;
}